<template>
  <el-container>
    <!-- 左侧导航栏 -->
    <el-aside width="220px">
      <el-container class="book-nav">
        <bookNavMenu @updateSelectedOptions="handleUpdateSelectedOptions" />
      </el-container>
    </el-aside>

    <!-- 右侧小说展示区 -->
    <el-main>
      <div>
        <NovelItem v-for="(novel, index) in novels" :key="index" :novel="novel" />
      </div>
    <div v-if=" pagination.totalRecords > 0 ">
      <!-- 分页组件 -->
      <el-pagination 
        background
        layout="prev, pager, next"
        :total="pagination.totalRecords"
        :page-size="pagination.size"
        :current-page="pagination.page"
        @current-change="handlePageChange"
        style="text-align: center; margin-top: 20px;"
      />
      </div>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import NovelItem from './components/NovelItem.vue';
import bookNavMenu from './components/bookNavMenu.vue';


// 父组件中的 selectedOptions 用于接收子组件传递的数据
const selectedOptions = ref({
  category: 0,
  status: 0,
  wordCount: 0,
  attribute: 0
});

// 分页数据
const pagination = ref({
  page: 1,         // 当前页
  size: 10,        // 每页条数
  totalPages: 1,   // 总页数
  totalRecords: 0  // 总记录数
});

// 小说数据
const novels = ref([]);

// 处理子组件传递的数据
const handleUpdateSelectedOptions = (newSelectedOptions: any) => {
  selectedOptions.value = { ...newSelectedOptions };
  fetchNovels(pagination.value.page, pagination.value.size);
};

// 获取小说数据
const fetchNovels = (page: number, size: number) => {
  axios.post(`/api/books/search?pageNum=${page}&pageSize=${size}`, {
    ...selectedOptions.value,
  }).then((res) => {
    console.log(res);
    const data = res.data.data;

    // 更新小说列表
    novels.value = data.listData;

    // 更新分页信息
    pagination.value.page = data.page;
    pagination.value.size = data.size;
    pagination.value.totalPages = data.totalPages;
    pagination.value.totalRecords = data.totalRecords;
  });
};

// 监听分页切换事件
const handlePageChange = (newPage: number) => {
  pagination.value.page = newPage;
  fetchNovels(newPage, pagination.value.size); // 请求新页数据
};

// 页面挂载时请求初始数据
onMounted(() => {
  fetchNovels(pagination.value.page, pagination.value.size);
});
</script>

<style scoped>
.book-nav {
  position: fixed; /* 固定导航栏 */
  top: 10%; /* 从顶部开始 */
  left: 0;
  margin-left: 20px;
  min-height: calc(100vh - 60%);
  max-height: calc(100vh - 20%);
  background-color: #f0f0f0;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  overflow-y: auto; /* 允许垂直滚动 */
}
</style>
